import router, { resetRouter } from '@/router'
import { login, loginSocial, signup, bind, getInfo, logout } from '@/api/system/user'
import { getStorage, setStorage, getAuthentication, setAuthentication, removeAuthentication } from '@/utils/store'
import Auth from '@/utils/auth'

const state = {
  token: getAuthentication(),
  info: {},
  roles: [],
  routes: []
}

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, {
      token: '',
      info: {},
      roles: []
    })
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INFO: (state, info) => {
    state.info = info
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { uname, pword } = userInfo
    const authenticationInfo = Auth.generate(uname, pword)
    userInfo.authenticationInfo = authenticationInfo

    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { param } = response
        if (param.value) {
          commit('SET_TOKEN', param.value)
          setAuthentication(param.value)
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 第三方自动登录
  socialLogin({ commit }, type, code, state) {
    return new Promise((resolve, reject) => {
      loginSocial(type, code, state).then(response => {
        const { param } = response
        // 已绑定，直接登录系统
        if (param.bind) {
          commit('SET_TOKEN', param.accessToken)
          setAuthentication(param.accessToken)
        }
        resolve(param)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 通过token登录
  quickLogin({ commit }, token) {
    commit('SET_TOKEN', token)
    setAuthentication(token)
  },

  // 注册
  signup({ commit }, data) {
    const { uname, pword } = data
    const authenticationInfo = Auth.generate(uname, pword)
    data.authenticationInfo = authenticationInfo

    return new Promise((resolve, reject) => {
      signup(data).then(response => {
        const { param } = response
        if (param.value) {
          commit('SET_TOKEN', param.value)
          setAuthentication(param.value)
        }
        resolve(param)
      }).catch(error => {
        reject(error)
      })
    })
  },

  bind({ commit }, type, data) {
    const { uname, pword } = data
    const authenticationInfo = Auth.generate(uname, pword)
    data.authenticationInfo = authenticationInfo

    return new Promise((resolve, reject) => {
      bind(data).then(response => {
        const { param } = response
        if (param.token) {
          commit('SET_TOKEN', param.value)
          setAuthentication(param.token)
        }
        resolve(param)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { user, member, permissions, tagsView } = response.param

        if (!user) {
          reject('获取登录信息失败，请重新登录')
        }

        if (member) {
          user.member = {
            id: member.levelId,
            name: member.levelName
          }
        }

        const tagsView_ = getStorage('tagsView') || tagsView
        setStorage('tagsView', tagsView_)

        commit('SET_INFO', user)
        commit('SET_ROLES', permissions)

        resolve({
          user,
          permissions
        })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 刷新用户信息
  updateInfo({ commit }, user) {
    return new Promise(resolve => {
      commit('SET_INFO', user)
      resolve()
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeAuthentication()
        resetRouter()
        commit('RESET_STATE')
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeAuthentication()
      commit('RESET_STATE')
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const { permissions } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', permissions, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
